import { formatTime } from "web-utils-super";

/**
 * 防抖
 * @param func {*}  执行函数
 * @param wait {*}  节流时间,毫秒
 */
const debounce = (func, wait) => {
  let timeout;
  return function () {
    let context = this;
    let args = arguments;

    if (timeout) clearTimeout(timeout);

    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
};

/**
 * 获取日期
 * @param num {*}  相对于今天想获取的日期，昨天的日期，num就是-1， 前天的就是-2
 * @param str 表示年月日间的分割方式
 */
const appGetNowDay = (num = 0, str = "-") => {
  var today = new Date();
  var nowTime = today.getTime();
  var ms = 24 * 3600 * 1000 * num;
  today.setTime(parseInt(nowTime + ms));
  var oYear = today.getFullYear();
  var oMoth = (today.getMonth() + 1).toString();
  if (oMoth.length <= 1) oMoth = "0" + oMoth;
  var oDay = today.getDate().toString();
  if (oDay.length <= 1) oDay = "0" + oDay;
  return oYear + str + oMoth + str + oDay;
};

function formatDateAndDay(timestamp) {
  const dateObj = new Date(timestamp);

  const days = [
    "星期天",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  const dayOfWeek = days[dateObj.getDay()]; // 获取星期几

  const formattedDate = formatTime(dateObj, "YY-MM-DD");
  return {
    date: formattedDate,
    day: dayOfWeek,
  };
}

const timeFun = (time, func, timer) => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  func()
  timer = setInterval(() => {
    func()
  }, time)
  return timer
}


export { debounce, appGetNowDay, formatDateAndDay, timeFun };
